import axios from 'axios';
import { MessageBox, Message } from 'element-ui'


const baseUrl = () => {
    const VUE_APP_API_TYPE = process.env.VUE_APP_API_TYPE;
    const urlObj = {
        dev: '/dev',     //开发
        qafc: '',        //测试
        pre: '',         //预发
        online: '',
    }
    if (process.env.NODE_ENV === 'development') {
        return urlObj.dev     //开发的时候用来切不同环境
    }
    return urlObj[VUE_APP_API_TYPE]
}

const instance = axios.create({
    baseURL: baseUrl(),
    timeout: 8000   
});


instance.interceptors.request.use(config => {
    // 设置header头 通过接口权限验证
    if(!config.headers['Content-Type']){
        config.headers['Content-Type'] = 'application/json';
    }
    config.headers['Authorization'] = sessionStorage.getItem('token') || ''
    return config;
});

instance.interceptors.response.use(response => {
    if (response.data.code === 200 && response.data.status == "success") {
        return Promise.resolve(response.data);
    } else {
        if(response.data.message === 'This action is unauthorized.'){
            Message.error('身份过期，请重新登录！');
            setTimeout(()=>{
                sessionStorage.clear()
                window.location.href = '/login'
            },1200)
            return
        }
        Message.error(response.data.message);
        return Promise.reject(response.data);   //直接用catch捕获
    }
}, error => {
    if(error.message.includes('timeout')){
        Message.error('请求超时，请刷新从试');
    }else if(error.message.includes('404')){
        Message.error('404');
    }
    return Promise.reject(error)
});


const get = (url, params = {}, config = {}) => {
    return instance({method: 'GET', url, params, ...config })
};
const post = (url, data = {}, config = {}) => {
    return instance({method: 'POST', url, data, ...config })
};
const put = (url, data, config = {}) => {
    return instance({method: "PUT", url, data, ...config})
};
const del = (url, data, config = {}) => {
    return instance({method: "DELETE", url, data, ...config})
};
export {get,post,put,del}


